package com.ada.tft_sport;

import android.app.ActionBar.LayoutParams;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.ada.mcu.service.Beep;
import com.ada.mcu.service.IContactUi;
import com.ada.mcu.service.IServiceCallback;
import com.ada.mcu.service.MachineData;
import com.ada.mcu.service.ProgramData;
import com.ada.mcu.service.ServiceRepliedData;
import com.ada.mcu.service.SettingData;
import com.ada.tft_sport.adapter.MyFragmentPagerAdapter;
import com.ada.tft_sport.fragment.LanguageFragment;
import com.ada.tft_sport.fragment.MainFragment;
import com.ada.tft_sport.fragment.MultimediaFragment;
import com.ada.tft_sport.fragment.ProgramFragment;
import com.ada.tft_sport.fragment.SchemaFragment;
import com.ada.tft_sport.fragment.StopSportFragment;
import com.ada.tft_sport.fragment.TvFragment;
import com.ada.tft_sport.utils.SharedPreferencesUtils;

import java.util.ArrayList;

public class MainActivity extends FragmentActivity implements OnClickListener {

	private MainActivity activity;
	private FragmentManager fm;
	private FragmentTransaction ft; // 碎片事务管理器
	private Fragment mainFragment; // 主界面
	private Fragment programFragment; // 程序界面
	private Fragment multimediaFragment; // 多媒体界面
	private Fragment schemaFragment; // 模式界面
	private Fragment languageFragment; // 语言界面
	private Fragment tvFragment; // TV界面
	private Fragment stopsportFragment;// 休息界面
	private Fragment startupFragment;

	private TextView iv_main;
	private TextView iv_program;
	private TextView iv_multimedia;
	private TextView iv_schema;
	private TextView iv_setting;
	private TextView iv_back;
	private ImageView iv_tv;
	private ImageView iv_play;
	private ImageView iv_language;

	private ViewPager mPager;
	private ArrayList<Fragment> fragmentList;

	private PopupWindow topPopupWindow;// top popupwindow
	private PopupWindow inputWeightpop;// inputWeightpop
	private PopupWindow bottompop;// inputWeightpop
	private Context mContext = null;

	public ServiceRepliedData data;
	// 下位机的定义
	private static final String TAG = "setActivity";
	public IContactUi mService;
	private ServiceConnection mConnection;
	public static MachineData mMachineData = null;
	public static int[] repliedBackup = { 0, 0, 0, 0, 0 };
	private final int UPDATE_RECEIVED_DATA = 1000;
	private final int UPDATE_UI_DATA = 1001;
	private IServiceCallback mCallback;
	// 以上是下位机定义

	// 包名
	public String extendPackageName;

	// 定义一个数据库
	// static SharedPreferences sharedPreferences = null;

	public static final String PREFS_NAME = "MyPrefsFile";
	public static final String FIRST_RUN = "first";
	private boolean first;

	// 按键板,选程式
	public static boolean isOrNoAtNowModeProjectActivity = false;
	public static boolean isOrNoAtsetFragment = true;
	public static boolean isOrNoSetPerFragment = false;
	public static boolean isOrNoFactoryPatternSetFragment = false;
	// 个人消耗信息
	public static int startEndMark = 0;
	public TextView TV_consumptionOk;
	public TextView TV_consumptionTimeShow;
	public TextView TV_consumptionDistanceShow;
	public TextView TV_consumptionCalorieShow;
	public TextView TV_consumptionSpeedShow;

	// 年龄身高体重的值
	public static String Age_Text = "35";
	public static String Height_Text = "168";
	public static String Weight_Text = "68";
	// 时间距离热量
	public String Time_Text = "30";
	public String Hot_Text = "20";
	public String Distance_Text = "3";

	// 选择模式后传给后台
	public ProgramData mProgramData;
	// 公英制
	public static String TempFactoryPatternSet = "";// 区别是选择了那个,键盘好去显示到对应的上面

	// 密码模块
	// 密码
	public static int password = 333999;
	public static boolean isOrNoChangeParameter = false;// 如果改了工程参数设置里面的最大值最小值
	// 公英制标记 0:公制 1：英制
	public static int defaultSing = 0;
	public static int defaultMinSpeed = 1;
	public static int defaultMaxSpeed = 20;
	public static int defaultMaxLncline = 20;
	public static int defaultSpeedTime = 2;// 对后台无用的
	public static int defaultWhell = 5;
	public static int defaultAutoOilDistance = 800;
	public static int defaultoilTime = 20;
	public static int defaultAddOliNumber = 25;// 加油报警次数

	public static int setDistanceLimit = 0;
	public static int lockDistance = 0;
	public boolean lock = false;// 设定锁机，开始计算距离
	public boolean locked = false;// 当前状态是否是锁机状态
	public static int lockDistanceTemp = 0;
	public static int setNumberSectionSpeed = 20;
	public static int useOrNoPassword = 1;

	public static int totalTimeValue = 0;
	public static int totalDistanceValue = 0;

	// 上面�?行显示数据的
	public TextView TV_Speed_Show_Top;
	public TextView TV_Speed;
	public TextView TV_Heart_Show_Top;
	public TextView TV_Heat_Show_Top;
	public TextView TV_Distance_Show_Top;
	public TextView TV_Distance;
	public TextView TV_Time_Show_Top;
	public TextView TV_GradiendShow_Top;

	private int caloryCount;
	private int milesCount;
	private static int timeCount;

	public Handler stepTimeHandler;
	public Runnable mTicker;
	long startTime = 0;

	// public SdcardStateChanageReceiver sdcardStateReceiver;

	public String SdState;
	public String Sdpath;

	// SlidingDrawer模块
	public SlidingDrawer slidingDrawerSet;
	public ImageButton handle;

	// 亮度

	private boolean sysAutomaticMode = false;
	// 声音

	private AudioManager audioManager; // 系统声音管理类
	private int maxVolume, currentVolume;
	private ToggleButton TB_toggleButtonMute;

	// wifi 下载
	public SeekBar SbWifi;
	public ImageView WiFi_ON;
	public ImageView WiFi_OFF;
	public SeekBar SB_Load;
	public ImageView Load_ON;
	public ImageView Load_OFF;
	// public wifiStateBroadcast mwifiStateBroadcast;
	public String wifiState;
	public ImageView mNetIcon;

	// public ImageView WiFi_offState;
	// public wifiStateBroadcast mwifiStateBroadcast;

	public Button Btn_SlidingSetting;
	public String getPassword = "";
	public Button Btn_SlidingMenu;

	public View LL_BackAndPause;
	public View RL_consumptionInformation;

	// 閺堬拷娑撳娼伴敍灞界毈閹稿鎸�
	public ImageButton IB_downSmall;

	// 4个按钮
	// 是否是程式状态，是的话四个按钮无效
	public boolean isORNoPatternState = false;
	public ImageButton IB_leftOnly;
	public ImageButton IB_leftBoth;
	public ImageButton IB_rightOnly;
	public ImageButton IB_rightBoth;

	// 返回按钮
	public Button Back;
	private Button pause;

	/*
	 * 类型标记 初始值0：点击4个按钮进度条不变化；点击 值为2：调节坡度点击IV_SpeedSliding 值为1：调节速度
	 */
	public static int TypeMark = 1;
	// 坡度图片
	public ImageView circle_point_imgGradient;

	public View RL_circle_point_imgGradient;
	public ImageView IV_GradientSliding;
	public static int progressGradient = 0;
	public TextView ProgressBarGradient;

	// 闁喎瀹抽崶鍓у
	public ImageView circle_point_imgSpeed;

	public ImageView IV_SpeedSliding;
	public static int progressSpeed = 10;

	public static int progressSpeedEnglish = 0;// 公英制转换用
	public static Double progressSpeedEnglishCircle = 0.0;// 公英制转换用
	public TextView CircleProgressBarSpeed;

	public int isWarningOpened = 0;
	public static int numCode = 0;

	public static int switchFragment = 0;
	private FragmentTransaction fragmentTransaction;

	public Boolean isOrNoFirstInProjectFragment = true;

	public Boolean isOrNoFirstInModeFragment = true;
	private Dialog dialog;

	public int programType = 0;
	public static final int HANDMOVE = 1;
	public static final int FLUCTUATE = 2;
	public static final int CLIMBING = 3;
	public static final int INTERVAL = 4;
	public static final int LOSTWEIGHT = 5;
	public static final int MOUNTION = 6;
	public static final int BURN = 7;

	public static final int HEART65 = 8;
	public static final int HEART75 = 9;
	public static final int HEART85 = 10;

	public static final int HOT = 11;
	public static final int DISTANCE = 12;
	public static final int TIME = 13;
	public static boolean isOrNoProgram = false;
	public boolean isOrNoClickStop = false;

	
	
	private int width;
	private int height;
	
	public View RL_commenTop;
	public int countDown = 0;// 倒计时区分进入setj界面还是task界面
	protected boolean isOrNoCountdown = true;
	public View popwindwow;
	private View popwindwow_bottom;
	public TextView pop_calorie;
	public TextView pop_distance;
	public TextView pop_time;
	String fitness_time, fitness_distance, fitness_calorie;// 用来存储数据

	
	private Handler uiUpdateHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			data = (ServiceRepliedData) msg.obj;

			
			Log.i("9999999999999","999999999999999"+mProgramData);
			//Log.i("mProgramData.getAge();111111111", "mProgramData.getAge();111111111"+mProgramData.getAge());
			// Log.i(TAG, "LYJ, mMachineData.getCurrentStatus():" +
			// mMachineData.getCurrentStatus());
			// Log.i("data.getAlarmCode()" , " "+data.getAlarmCode());
			// Log.i("isWarningOpened" ," "+isWarningOpened);
			if (locked && switchFragment != 13) {
				switchFragment = 13;

			}

			int currentStatus = mMachineData.getCurrentStatus();
			if (currentStatus == 1) {
				Log.i("状态是1 startEndMark", " " + startEndMark);
				startEndMark = 1;
			}

			if (currentStatus != 0 && currentStatus != 3) {
				repliedBackup[0] = data.getTimeCount();
				repliedBackup[1] = data.getMiles();
				repliedBackup[2] = data.getCalories();
				repliedBackup[3] = mMachineData.getOperatingFrequency();
				repliedBackup[4] = mProgramData.getProgramIndex();
				// Log.i(TAG, "LYJ " + repliedBackup[0] + " " + repliedBackup[1]
				// + " " + repliedBackup[2] + " " + repliedBackup[3] + " "
				// + repliedBackup[4]);
			} else if (currentStatus == 0 && data.getAlarmCode() == 0
					&& isWarningOpened == 0) {
				// 任务完成显示个人消耗信息
				Log.i("startEndMark", " " + startEndMark);
				if (startEndMark == 1) {
					startEndMark = 0;
					mProgramData.reset();
					if (lockDistance <= setDistanceLimit
							&& setDistanceLimit >= 0 && locked == false) {
						pressStopShowConsumeDialogue();
					}
				}
			} else if (currentStatus == 3) {
				if (data.getSelfCheckStatus() == 1) {
					warning();
				} else if (locked == false) {
					switchFragment = 0;
					// switchFragment(switchFragment);
				}
			}
			// Log.i("data.getAlarmCode()", ""+data.getAlarmCode());
			if ((data.getAlarmCode() != 0) && (isWarningOpened == 0)) {
				isWarningOpened = 1;
				numCode = data.getAlarmCode();
				// Log.i("data.getAlarmCode()", "" + data.getAlarmCode());

				// 警告
				warning();
			}
			// Log.i("data.getSelfCheckStatus()", ""+data.getSelfCheckStatus());

			TextView pop_bottom_speed = (TextView) popwindwow_bottom
					.findViewById(R.id.pop_bottom_speed);
			switch (msg.what) {
			case UPDATE_RECEIVED_DATA:

				// 速度

				pop_bottom_speed.setText(""
						+ mMachineData.getOperatingFrequency());
				// 速度控制
				ImageView pop_bottom_speed_add = (ImageView) popwindwow_bottom
						.findViewById(R.id.pop_bottom_speed_add);
				ImageView pop_bottom_speed_sub = (ImageView) popwindwow_bottom
						.findViewById(R.id.pop_bottom_speed_sub);
				pop_bottom_speed_add.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub

						mMachineData.setOperatingFrequency(mMachineData
								.getOperatingFrequency() + 1);
						try {
							if (null != mService) {
								mService.updateToMcu(mMachineData);
							}
						} catch (RemoteException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});

				pop_bottom_speed_sub.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						mMachineData.setOperatingFrequency(mMachineData
								.getOperatingFrequency() - 1);
						try {
							if (null != mService) {
								mService.updateToMcu(mMachineData);
							}
						} catch (RemoteException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});

				ImageView pop_bottom_destory = (ImageView) popwindwow_bottom
						.findViewById(R.id.pop_bottom_destory);
				ImageView pop_bottom_play = (ImageView) popwindwow_bottom
						.findViewById(R.id.pop_bottom_play);
				ImageView pop_bottom_stop = (ImageView) popwindwow_bottom
						.findViewById(R.id.pop_bottom_stop);
				ImageView pop_bottom_slow = (ImageView) popwindwow_bottom
						.findViewById(R.id.pop_bottom_slow);

				// 直接停止跑步机
				pop_bottom_destory.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						mMachineData.setCurrentStatus(0);
						try {
							if (null != mService) {
								mService.updateToMcu(mMachineData);
							}
						} catch (RemoteException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						fitness_time = pop_time.getText().toString().trim();
						fitness_distance = pop_distance.getText().toString()
								.trim();
						fitness_calorie = pop_calorie.getText().toString()
								.trim();
						SharedPreferencesUtils.putString(MainActivity.this,
								"fitness_timeInfo", "fitness_time",
								fitness_time);
						SharedPreferencesUtils.putString(MainActivity.this,
								"fitness_distanceInfo", "fitness_distance",
								fitness_distance);
						SharedPreferencesUtils.putString(MainActivity.this,
								"fitness_calorieInfo", "fitness_calorie",
								fitness_calorie);
						mPager.setCurrentItem(6);
						bottompop.dismiss();
						// 清除顶部pop
						if (topPopupWindow != null
								&& topPopupWindow.isShowing()) {
							topPopupWindow.dismiss();
							topPopupWindow = null;
						}
					}
				});

				pop_bottom_play.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						mMachineData.setCurrentStatus(1);
						try {
							if (null != mService) {
								mService.updateToMcu(mMachineData);
							}
						} catch (RemoteException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						showPopupWindow();
					}
				});
				// 暂停跑步机
				pop_bottom_stop.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						mMachineData.setCurrentStatus(2);
						try {
							if (null != mService) {
								mService.updateToMcu(mMachineData);
							}
						} catch (RemoteException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						fitness_time = pop_time.getText().toString().trim();
						fitness_distance = pop_distance.getText().toString()
								.trim();
						fitness_calorie = pop_calorie.getText().toString()
								.trim();
						SharedPreferencesUtils.putString(MainActivity.this,
								"fitness_timeInfo", "fitness_time",
								fitness_time);
						SharedPreferencesUtils.putString(MainActivity.this,
								"fitness_distanceInfo", "fitness_distance",
								fitness_distance);
						SharedPreferencesUtils.putString(MainActivity.this,
								"fitness_calorieInfo", "fitness_calorie",
								fitness_calorie);
						mPager.setCurrentItem(6);
					}
				});

				// 缓和
				pop_bottom_slow.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						for (int i = 0; i < 3; i++) {
							delay(1000); // 延时1秒
							mMachineData.setOperatingFrequency(mMachineData
									.getOperatingFrequency() - 5);

							try {
								if (null != mService) {
									mService.updateToMcu(mMachineData);
								}
							} catch (RemoteException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						}
					}

					private void delay(int i) {
						// TODO Auto-generated method stub
						try {
							Thread.currentThread();
							Thread.sleep(i);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				});

				// 坡度
				TextView pop_bottom_incline = (TextView) popwindwow_bottom
						.findViewById(R.id.pop_bottom_incline);
				pop_bottom_incline.setText("" + mMachineData.getIncline());

				// 坡度控制
				ImageView pop_bottom_incline_add = (ImageView) popwindwow_bottom
						.findViewById(R.id.pop_bottom_incline_add);
				ImageView pop_bottom_incline_sub = (ImageView) popwindwow_bottom
						.findViewById(R.id.pop_bottom_incline_sub);
				pop_bottom_incline_add
						.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View arg0) {
								// TODO Auto-generated method stub
								mMachineData.setIncline(mMachineData
										.getIncline() + 1);
								try {
									if (null != mService) {
										mService.updateToMcu(mMachineData);
									}
								} catch (RemoteException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						});
				pop_bottom_incline_sub
						.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View arg0) {
								// TODO Auto-generated method stub
								mMachineData.setIncline(mMachineData
										.getIncline() - 1);
								try {
									if (null != mService) {
										mService.updateToMcu(mMachineData);
									}
								} catch (RemoteException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						});
				pop_time = (TextView) popwindwow.findViewById(R.id.pop_time);
				TextView pop_heart_rate = (TextView) popwindwow
						.findViewById(R.id.pop_heart_rate);
				// 心率
				pop_heart_rate.setText("" + (data.getHeartBeat() & 0xff));
				Log.i("跑步机心率", "" + data.getHeartBeat());
				// 时间
				pop_time.setText(formatIntToTime(data.getTimeCount()));
				// // Log.i("repliedBackup[0]", ""+repliedBackup[0]);
				// // Log.i("repliedBackup[1]", ""+repliedBackup[1]);
				// // Log.i("repliedBackup[2]", ""+repliedBackup[2]);
				// // Log.i("repliedBackup[3]", ""+repliedBackup[3]);
				// // Log.i("时间显示", formatIntToTime(data.getTimeCount()));

				// ***************
				int distanceResultString = data.getMiles();
				int head = distanceResultString / 100;
				int tail = distanceResultString % 100;
				String pointRightText = "";
				if (tail / 100 > 0) {
					pointRightText = "" + tail;
				} else if (tail / 10 > 0) {
					pointRightText = "" + tail;
				} else {
					pointRightText = "0" + tail;
				}
				// *********************
				pop_distance = (TextView) popwindwow
						.findViewById(R.id.pop_distance);
				pop_calorie = (TextView) popwindwow
						.findViewById(R.id.pop_calorie);
				// 距离
				// pop_distance.setText( "" +data.getMiles());

				pop_distance.setText(head + "." + pointRightText);
				long currentCalorie = data.getCalories();
				tail = (int) currentCalorie % 1000;
				if (tail / 100 > 0) {
					pointRightText = "" + tail;
				} else if (tail / 10 > 0) {
					pointRightText = "0" + tail;
				} else {
					pointRightText = "00" + tail;
				}
				// 卡路里
				pop_calorie.setText(currentCalorie / 1000 + "."
						+ pointRightText);

				// metricAndEnglishSwitch(mMachineData.getOperatingFrequency());
				//
				// gradientShow(mMachineData.getIncline());
				// -----------------------------
				// if (data.getExecutionMiles() / 100000>0) {
				// totalDistanceValue = (int) data.getExecutionMiles() / 100000;
				// Log.i("lock", ""+lock);
				// Log.i("WDHtotalDistanceValue", ""+totalDistanceValue);
				// Log.i("WDHsetDistanceLimit", ""+setDistanceLimit);
				// Log.i("WDHlockDistanceTemp", ""+lockDistanceTemp);
				// Log.i("WDHlockDistance", ""+lockDistance);
				// if (!lock) {
				// lockDistanceTemp = totalDistanceValue;//没锁机暂存距离
				// }else {
				// lockDistance = totalDistanceValue-lockDistanceTemp;//锁机后计算距离
				//
				// if (lockDistance>=setDistanceLimit && setDistanceLimit>=1) {
				// mMachineData.setCurrentStatus(0);
				// try {
				// if (null != mService) {
				// mService.updateToMcu(mMachineData);
				// }
				// } catch (RemoteException e) {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// }
				// updateToService();
				// locked = true;
				// setPasswordFlieDate();//进入就写入文件，防止断电数据丢失，保证重启后跑步机不能用
				// if (switchFragment != 13) {
				// switchFragment = 13;
				// switchFragment(switchFragment);
				// }
				// }
				// }
				// }
				//
				// if (data.getExecutionTime() / 3600 > 0) {
				// totalTimeValue = data.getExecutionTime() / 3600;}
				// // Log.i("totalTimeValue", ""+totalTimeValue);
				// // Log.i("totalDistanceValue", ""+totalDistanceValue);
				break;
			case UPDATE_UI_DATA:
				break;
			}
		}

		private void warning() {
			// TODO Auto-generated method stub

		}

		private void pressStopShowConsumeDialogue() {

			Log.i("dialog", "进入消耗信息");
			// 按键板停止不用发给后台状态
			TypeMark = 1;// 让焦点回到速度上
			// this.programType = 0;
			// startEndMark = 0;
			// LayoutInflater inflater = (LayoutInflater)
			// this.getSystemService(LAYOUT_INFLATER_SERVICE);
			// View layout = inflater.inflate(R.layout.consumption_information,
			// null);
			//
			// TV_consumptionTimeShow = (TextView) layout
			// .findViewById(R.id.TV_consumptionTimeShow);
			// TV_consumptionDistanceShow = (TextView) layout
			// .findViewById(R.id.TV_consumptionDistanceShow);
			// TV_consumptionSpeedShow = (TextView) layout
			// .findViewById(R.id.TV_consumptionSpeedShow);
			// TV_consumptionCalorieShow = (TextView) layout
			// .findViewById(R.id.TV_consumptionCalorieShow);
			// TV_consumptionOk = (TextView) layout
			// .findViewById(R.id.TV_consumptionOk);

			Log.i("repliedBackup[0]", "" + repliedBackup[0]);
			Log.i("repliedBackup[1]", "" + repliedBackup[1]);
			Log.i("repliedBackup[2]", "" + repliedBackup[2]);
			Log.i("repliedBackup[3]", "" + repliedBackup[3]);
			Log.i("repliedBackup[4]", "" + repliedBackup[4]);

			//Log.i(" Integer.parseInt(Time_Text)", Time_Text);

			if (isOrNoProgram) {
				if (repliedBackup[4] == TIME || repliedBackup[4] == HANDMOVE
						|| repliedBackup[4] == FLUCTUATE
						|| repliedBackup[4] == CLIMBING
						|| repliedBackup[4] == INTERVAL
						|| repliedBackup[4] == LOSTWEIGHT
						|| repliedBackup[4] == MOUNTION
						|| repliedBackup[4] == BURN) {
					if (isOrNoClickStop) {
						TV_consumptionTimeShow
								.setText(":   "
										+ formatIntToTime(((Integer
												.parseInt(Time_Text) * 60) - repliedBackup[0])));
					} else {
						TV_consumptionTimeShow
								.setText(":   "
										+ formatIntToTime(Integer
												.parseInt(Time_Text) * 60));
					}
				} else {
					TV_consumptionTimeShow.setText(":   "
							+ formatIntToTime(repliedBackup[0]));
				}
				isOrNoProgram = false;
			} else {
				TV_consumptionTimeShow.setText(":   "
						+ formatIntToTime(repliedBackup[0]));
			}

			String temp;
			int distanceResultString;
			if (repliedBackup[4] == DISTANCE) {
				if (isOrNoClickStop) {
					distanceResultString = (Integer.parseInt(Distance_Text) * 1000 - repliedBackup[1]);
				} else {
					distanceResultString = (Integer.parseInt(Distance_Text) * 1000);
				}
			} else {
				distanceResultString = repliedBackup[1];
			}
//			Log.i("mProgramData.getGoal() / 100", "" + mProgramData.getGoal()
//					/ 100);
			
			int head = distanceResultString / 1000;
			int tail = distanceResultString % 1000;
			String pointRightText = "";
			if (tail / 100 > 0) {
				pointRightText = "" + tail;
			} else if (tail / 10 > 0) {
				pointRightText = "0" + tail;
			} else {
				pointRightText = "00" + tail;
			}
			temp = head + "." + pointRightText;
			if (defaultSing == 0) {
				TV_consumptionDistanceShow.setText(":  " + temp + " km");
			} else {
				TV_consumptionDistanceShow.setText(":  " + temp + " Mile");
			}

			int currentCalorie;
			if (repliedBackup[4] == HOT) {
				if (isOrNoClickStop) {
					currentCalorie = Integer.parseInt(Hot_Text) * 1000
							- repliedBackup[2];
					Log.i("currentCalorie", "热量1" + currentCalorie);
				} else {
					currentCalorie = Integer.parseInt(Hot_Text) * 1000;
					Log.i("currentCalorie", "热量2" + currentCalorie);
				}
			} else {
				currentCalorie = repliedBackup[2];
			}

			tail = (int) currentCalorie % 1000;
			if (tail / 100 > 0) {
				pointRightText = "" + tail;
			} else if (tail / 10 > 0) {
				pointRightText = "0" + tail;
			} else {
				pointRightText = "00" + tail;
			}
			temp = "" + currentCalorie / 1000 + "." + pointRightText;
			TV_consumptionCalorieShow.setText(":   " + temp + " kCal");

			if (defaultSing == 0) {
				TV_consumptionSpeedShow.setText(":   " + repliedBackup[3] / 10
						+ "." + repliedBackup[3] % 10 + " km/h");
			} else {
				TV_consumptionSpeedShow.setText(":   " + repliedBackup[3] / 100
						* 6 + "." + repliedBackup[3] % 100 * 6 + " Mile/h");
			}

			isOrNoClickStop = false;
			if (null == dialog) {
				dialog = new Dialog(MainActivity.this);
			} else {
				dialog.show();
			}

			TV_consumptionOk.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					Beep.beep(getApplicationContext());
					switchFragment = 0;
					dialog.dismiss();
					dialog = null;

				}
			});

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		initpop();
		init();
		click();
		initViewpager();
		initConnecion();
		startService();
		// switchFragment(0); // 调用界面切换方法
	}

	/*
	 * 初始化pop窗口
	 */
	private void initpop() {
		// TODO Auto-generated method stub
		if (mMachineData == null)
			mMachineData = MachineData.getInstance();
		mProgramData = ProgramData.getInstance();

		LayoutInflater mLayoutInflater = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		popwindwow = mLayoutInflater.inflate(R.layout.pop_window, null);
		LayoutInflater mLayoutInflater1 = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		popwindwow_bottom = mLayoutInflater1.inflate(R.layout.popwindow_bottom,
				null);
	}

	/*
	 * 启动后台
	 */
	private void startService() {
		// TODO Auto-generated method stub
		Intent intent = new Intent("com.ada.mcu.service.BIND_SERVICE");
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		stopService(new Intent("com.ada.mcu.service.BIND_SERVICE"));
		super.onDestroy();
	}

	private void initConnecion() {
		mCallback = new IServiceCallback.Stub() {

			@Override
			public void responseToUi(ServiceRepliedData data)
					throws RemoteException {
				Message message = Message.obtain();
				message.obj = data;
				message.what = UPDATE_RECEIVED_DATA;
				uiUpdateHandler.sendMessage(message);
				Log.i("222222", ".............");
			}

			@Override
			public void sendSettingData(SettingData data)
					throws RemoteException {
				// TODO Auto-generated method stub

			}
		};

		mConnection = new ServiceConnection() {

			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				// TODO Auto-generated method stub
				mService = IContactUi.Stub.asInterface(service);
				try {
					/*
					 * if(mService.isInited()) {
					 * mService.registerCallback(mCallback); } else {
					 * exitService(); }
					 */

					Log.i(TAG, "onServiceConnected");
					mService.registerCallback("com.ada.tft_sport", mCallback);

				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onServiceDisconnected(ComponentName name) {
				mService = null;
			}
		};
	}

	private void initViewpager() {
		mPager = (ViewPager) findViewById(R.id.viewPager);
		fragmentList = new ArrayList<>();

		mainFragment = new MainFragment();
		programFragment = new ProgramFragment();
		multimediaFragment = new MultimediaFragment();
		schemaFragment = new SchemaFragment();
		languageFragment = new LanguageFragment();
		tvFragment = new TvFragment();
		stopsportFragment = new StopSportFragment();

		fragmentList.add(mainFragment);
		fragmentList.add(programFragment);
		fragmentList.add(multimediaFragment);
		fragmentList.add(schemaFragment);
		fragmentList.add(tvFragment);
		fragmentList.add(languageFragment);
		fragmentList.add(stopsportFragment);

		// 给ViewPager设置适配器
		mPager.setAdapter(new MyFragmentPagerAdapter(
				getSupportFragmentManager(), fragmentList));
		mPager.setCurrentItem(0);// 设置当前显示标签页为第一页
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());// 页面变化时的监听器
	}

	/**
	 * 查找界面上的元素
	 */
	private void init() {
		// TODO Auto-generated method stub
		DisplayMetrics metric = new DisplayMetrics(); 
		getWindowManager().getDefaultDisplay().getMetrics(metric); 
		width = metric.widthPixels; // 屏幕宽度（像素） 
		height = metric.heightPixels; // 屏幕高度（像素） 
		iv_main = (TextView) this.findViewById(R.id.iv_main);
		iv_program = (TextView) this.findViewById(R.id.iv_program);
		iv_multimedia = (TextView) this.findViewById(R.id.iv_multimedia);
		iv_schema = (TextView) this.findViewById(R.id.iv_schema);
		iv_setting = (TextView) this.findViewById(R.id.iv_setting);
		iv_back = (TextView) this.findViewById(R.id.iv_back);
		iv_tv = (ImageView) this.findViewById(R.id.iv_tv);
		iv_play = (ImageView) this.findViewById(R.id.iv_play);
		iv_language = (ImageView) this.findViewById(R.id.iv_language);

	}

	/**
	 * imageview事件监听类
	 */
	public class IvListener implements OnClickListener {
		private int index = 0;

		public IvListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			mPager.setCurrentItem(index);
		}
	}

	private void click() {
		// TODO Auto-generated method stub
		iv_main.setOnClickListener(new IvListener(0));
		iv_program.setOnClickListener(new IvListener(1));
		iv_multimedia.setOnClickListener(new IvListener(2));
		iv_schema.setOnClickListener(new IvListener(3));
		iv_setting.setOnClickListener(this);
		iv_back.setOnClickListener(this);
		iv_tv.setOnClickListener(new IvListener(4));
		iv_play.setOnClickListener(this);
		iv_language.setOnClickListener(new IvListener(5));
	}

	/**
	 * 监听事件
	 * 
	 * @param
	 */
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.iv_main:
			break;
		case R.id.iv_program:
			break;
		case R.id.iv_multimedia:
			break;
		case R.id.iv_schema:
			break;
		case R.id.iv_setting:
			Intent intent = this.getPackageManager().getLaunchIntentForPackage(
					"com.android.settings");
			startActivity(intent);
			break;
		case R.id.iv_back:
			onBackPressed();
			break;
		case R.id.iv_tv:
			break;
		case R.id.iv_play:

			mMachineData.setCurrentStatus(1);
			try {
				if (null != mService) {
					mService.updateToMcu(mMachineData);
				}
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			showPopupWindow();
			bottomPopWindow();
			break;
		case R.id.iv_language:
			break;
		}
	}

	/**
	 * 显示主界面上方中间的PopupWindow
	 */

	private void showPopupWindow() {

		if (null == topPopupWindow || !topPopupWindow.isShowing()) {
			TextView tv_pop_input_weight = (TextView) popwindwow
					.findViewById(R.id.pop_input_weight);
			tv_pop_input_weight.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					inputWeightPopWindow();

				}

			});

			topPopupWindow = new PopupWindow(popwindwow,
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			topPopupWindow.showAtLocation(findViewById(R.id.LinearLayout1),
					Gravity.CENTER | Gravity.TOP, -58, 0);
			topPopupWindow.setBackgroundDrawable(new BitmapDrawable());
			topPopupWindow.setOutsideTouchable(true);

		}
	}

	/**
	 * 显示输入体重的PopupWindow
	 */

	private void inputWeightPopWindow() {
		// TODO Auto-generated method stub

		
		
//		Log.i("ddddddd", "111111111111111"+width);
//		Log.i("bbbbbbbb", ""+height);
//		float density = metric.density; // 屏幕密度（0.75 / 1.0 / 1.5） 
//		int densityDpi = metric.densityDpi; // 屏幕密度DPI（120 / 160 / 240） 
		if (null == inputWeightpop || !inputWeightpop.isShowing()) {
			LayoutInflater mLayoutInflater = (LayoutInflater) this
					.getSystemService(LAYOUT_INFLATER_SERVICE);
			View popwindwow_weight = mLayoutInflater.inflate(
					R.layout.popwindow_input_weight, null);
			if(width==1280 && height==720){
				inputWeightpop = new PopupWindow(popwindwow_weight, 360, 195);
			}else{
				inputWeightpop = new PopupWindow(popwindwow_weight, 500, 285);
			}
                
			
			inputWeightpop.showAtLocation(findViewById(R.id.LinearLayout1),
					Gravity.CENTER | Gravity.TOP, -200, 168);
			inputWeightpop.setBackgroundDrawable(new BitmapDrawable());
			inputWeightpop.setOutsideTouchable(true);

			final TextView weight = (TextView) popwindwow_weight
					.findViewById(R.id.input_weight);
			TextView one = (TextView) popwindwow_weight.findViewById(R.id.one);
			TextView two = (TextView) popwindwow_weight.findViewById(R.id.two);
			TextView three = (TextView) popwindwow_weight
					.findViewById(R.id.three);
			TextView four = (TextView) popwindwow_weight
					.findViewById(R.id.four);
			TextView five = (TextView) popwindwow_weight
					.findViewById(R.id.five);
			TextView six = (TextView) popwindwow_weight.findViewById(R.id.six);
			TextView seven = (TextView) popwindwow_weight
					.findViewById(R.id.seven);
			TextView eight = (TextView) popwindwow_weight
					.findViewById(R.id.eight);
			TextView night = (TextView) popwindwow_weight
					.findViewById(R.id.night);
			TextView zero = (TextView) popwindwow_weight
					.findViewById(R.id.zero);
			TextView delete = (TextView) popwindwow_weight
					.findViewById(R.id.delete);
			TextView enter = (TextView) popwindwow_weight
					.findViewById(R.id.enter);

			one.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					String i = (String) weight.getText();
					weight.setText(i + 1);
				}
			});
			two.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					String i = (String) weight.getText();
					weight.setText(i + 2);
				}
			});
			three.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					String i = (String) weight.getText();
					weight.setText(i + 3);
				}
			});
			four.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					String i = (String) weight.getText();
					weight.setText(i + 4);
				}
			});
			five.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					String i = (String) weight.getText();
					weight.setText(i + 5);
				}
			});
			six.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					String i = (String) weight.getText();
					weight.setText(i + 6);
				}
			});
			seven.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					String i = (String) weight.getText();
					weight.setText(i + 7);
				}
			});
			eight.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					String i = (String) weight.getText();
					weight.setText(i + 8);
				}
			});
			night.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					String i = (String) weight.getText();
					weight.setText(i + 9);
				}
			});
			zero.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					String i = (String) weight.getText();
					weight.setText(i + 0);
				}
			});
			delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					weight.setText("");
				}
			});
			enter.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					if (weight.getText().equals("") == false) {
						if (weight.getText().length() <= 3) {
							int weight_value = Integer.parseInt((String) weight
									.getText());
							mProgramData.setWeight(weight_value);
							Toast.makeText(getApplicationContext(),
									getResources().getString(R.string.prompt1 )+ weight.getText() + "kg",
									Toast.LENGTH_SHORT).show();
							weight.setText("");
						} else {
							Toast.makeText(getApplicationContext(),
									getResources().getString(R.string.prompt2 ), Toast.LENGTH_SHORT).show();
						}
					} else {
						Toast.makeText(getApplicationContext(), getResources().getString(R.string.prompt3 ),
								Toast.LENGTH_SHORT).show();
					}
				}
			});
		}

	}

	/**
	 * 显示底部的PopupWindow
	 */

	private void bottomPopWindow() {
		// TODO Auto-generated method stub

		if (null == bottompop || !bottompop.isShowing()) {

			
			if(width==1280 && height==720){
				bottompop = new PopupWindow(popwindwow_bottom, 1148, 116);
			}else{
				bottompop = new PopupWindow(popwindwow_bottom, 1666, 166);
			}
			
			bottompop.showAtLocation(findViewById(R.id.LinearLayout1),
					Gravity.CENTER | Gravity.BOTTOM, 0, 0);
			bottompop.setBackgroundDrawable(new BitmapDrawable());
			bottompop.setOutsideTouchable(true);

		}

	}

	/**
	 * 去除主界面上方中间的PopupWindow和输入体重的inputWeightpop
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (inputWeightpop != null && inputWeightpop.isShowing()) {
			inputWeightpop.dismiss();
			inputWeightpop = null;
		}
		if (topPopupWindow != null && topPopupWindow.isShowing()) {
			topPopupWindow.dismiss();
			topPopupWindow = null;
		}
		return super.onTouchEvent(event);
	}

	/**
	 * 页面变化时的监听器，暂时为空
	 */
	public class MyOnPageChangeListener implements
			ViewPager.OnPageChangeListener {

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPageSelected(int arg0) {
			// TODO Auto-generated method stub
		}
	}

	// 时间以指定格式显示 .............工具类

	private String formatIntToTime(int timeCount) {
		String hh = timeCount / 3600 > 9 ? timeCount / 3600 + "" : "0"
				+ timeCount / 3600;
		String mm = (timeCount % 3600) / 60 > 9 ? (timeCount % 3600) / 60 + ""
				: "0" + (timeCount % 3600) / 60;
		String ss = (timeCount % 3600) % 60 > 9 ? (timeCount % 3600) % 60 + ""
				: "0" + (timeCount % 3600) % 60;
		return (hh + ":" + mm + ":" + ss);
	}

}
